<template>
	<view class="index">
		<button class="getaddress" @click="getaddress">
			获取地址
		</button>
		<view>
			{{address}}
		</view>
		<button class="getaddress" @click="getaddress">
			转账
		</button>
	</view>
</template>

<script>
	// 引入ERC20合约的ABI
	import erc20abi from "@/static/abis/erc20.json"
	import {
		ethers
	} from "ethers";
	// 定义成全局的,方便其他方法的调用
	var provider, signer, greet

	export default {
		data() {
			return {
				address: "",
			}
		},
		onLoad() {
			// 一般情况是刚进来就获取
			this.getaddress()
		},
		methods: {
			async getaddress() {
			provider = new ethers.providers.Web3Provider(window.ethereum)
			signer = provider.getSigner();
			let accounts = await provider.send("eth_requestAccounts", []);
			this.address = accounts[0]
			},
			async zhuanzhang() {
				uni.showLoading({
					title: "合约请求中"
				})
				//greet为生成的合约对象，需要注意的是signer参数，如果传进去就可以直接调用合约的修改方法
				let greet = new ethers.Contract("0x55d398326f99059ff775485246999027b3197955", erc20abi, signer);
				//调用合约的相关方法，parseEther是一个方法，可以将数字补18个0
				let data = await greet.transfer("to地址", ethers.utils.parseEther(String(this.config
						.superNodePrice)))
					.catch(function(err) {
						uni.showModal({
							title: "提示",
							showCancel: false,
							content: "操作失败，主动取消或余额不足"
						})
						uni.hideLoading()
						return
					})

				if (data.hash) {
					let data2 = await provider.waitForTransaction(data.hash);
					uni.hideLoading()
					uni.$emit('getaccount');
					uni.showModal({
						title: "提示",
						showCancel: false,
						content: "购买成功，因区块确认原因可能会有一两分钟延迟",
						success() {
							uni.navigateBack()
						}
					})
				} else {
					uni.hideLoading()
					uni.showModal({
						title: "提示",
						showCancel: false,
						content: "操作失败，余额不足"
					})
				}
			},
		}
	}
</script>

<style lang="less" scoped>

</style>